/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import entities.City;
import entities.Nation;
import entities.Place;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Alberto, Alessandra
 */
@Stateless
public class PlaceManager {
    
    private static final Logger logger = Logger.getLogger("PlaceManager");
    
    @PersistenceContext
    EntityManager em;
    
    public ArrayList<Nation> getAllNations () {
        ArrayList<Nation> nations = new ArrayList<>();
        nations.addAll(em.createNamedQuery("findAll" , Nation.class).getResultList());
        return nations;
    }
    
    public ArrayList<City> getCitiesByNation (Nation nation) {
        ArrayList<City> cities = new ArrayList<>();
        cities.addAll(em.createNamedQuery("findAllByNation", City.class)
                .setParameter("Cnation", nation).getResultList());
        return cities;
    }
    
    public Nation getNation (String name) {
        return em.createNamedQuery("findByName", Nation.class).setParameter("Nname", name).getSingleResult();
    }
    
    public City getCity (String name, Nation nation) {
        return em.createNamedQuery("findByNameAndNation", City.class)
                .setParameter("Cname", name).setParameter("Cnation", nation).getSingleResult();
    }
    
    public Place createPlace (String address, City city) {
        Place place = new Place(address, city);
        city.addPlace(place);
        em.persist(place);
        return place;
    }
    
    public void modifyPlace (Place place, City city) {
        place.getCity().removePlace(place);
        city.addPlace(place);
        place.setCity(city);
        em.merge(place);
    }
    
}
